import requests
from flask import request

from blues.cluster import bp
from config import UA
from model.cluster import Cluster


@bp.route('/api/v1/cluster/<cluster_id>/<namespace>/pods/')
def GetPodsBySelector(cluster_id, namespace):
    selector = request.args.get('selector')
    c = Cluster()
    cluster = c.find_by_id(cluster_id)
    # 调用k8s apiserver
    url = cluster['apiserver'] + "/api/v1/namespaces/" + namespace + "/pods/?labelSelector=" + selector
    headers = {"Authorization": "Bearer " + cluster['token'], "User-Agent": UA}
    response = requests.get(url=url, headers=headers, verify=False)
    # print(response.text)
    try:
        return response.json()
    except Exception as e:
        print(e)
        return ''


@bp.route('/api/v1/cluster/<cluster_id>/<namespace>/containers/<pod>')
def GetPod(cluster_id, namespace, pod):
    c = Cluster()
    cluster = c.find_by_id(cluster_id)
    # 调用k8s apiserver
    url = cluster['apiserver'] + "/api/v1/namespaces/" + namespace + "/pods/" + pod
    headers = {"Authorization": "Bearer " + cluster['token'], "User-Agent": UA}
    response = requests.get(url=url, headers=headers, verify=False)
    # print(json2yaml(response.text))
    try:
        return response.json()
    except Exception as e:
        print(e)
        return ''
